/**
 * 登录页面
 * @author xiaoxujs
 */
import { useNavigate } from "react-router-dom";
import { Button, ConfigProvider, Input, message } from "antd";
import { LoginBox, TopBox, CardBox } from "./style";
import { useEffect, useState } from "react";
import { basicIp } from "../../api/http";
import { handleRandomString } from "../../assets/fun/suijiStr";
import { postContextLogin } from "../../api/login";
import { ILoginData, ISessionUserData } from "../../type/login";
import { useWindowFontSize } from "../../assets/fun/Antd/configprovider";
import { getAllDictionaryEntries } from "../../assets/fun/DictionaryItem";
import { IMenuTree } from "../../type/antd";


const LoginPage = () => {
  const navigate = useNavigate();
  const [imageBase64, setImageBase64] = useState<string>(); // 图片验证码
  const [codeValue, setCodeValue] = useState<string>(); // 验证码
  const [loginName, setLoginName] = useState<string>(); //登录账号
  const [password, setPassword] = useState<string>(); //登录密码
  const [suijishuValue, setSuijishuValue] = useState(handleRandomString());

  useEffect(() => {
    setImageBase64(`${basicIp}/context/captcha/${suijishuValue}`);
  }, [suijishuValue])

  //点击切换验证码
  const handleImageRenovate = () => {
    setSuijishuValue(handleRandomString())
  };

  //获取第一个页面
  const handleOneUrl = (data: IMenuTree[], defaultMenu: {
    defaultOpenKeys: string[],
    defaultSelectedKeys: string[],
  }) => {
    data.forEach(element => {
      if (defaultMenu.defaultSelectedKeys.length === 0) {
        if (element.url.indexOf('/') > -1) {
          defaultMenu.defaultSelectedKeys.push(element.url)
        } else {
          defaultMenu.defaultOpenKeys.push(element.url)
        }
      }
      if (element.children.length > 0) {
        handleOneUrl(element.children, defaultMenu)
      }
    });

  }
  // 登录
  const handleLogin = async () => {
    if (!loginName) {
      message.warning("请输入账号！");
    } else if (!password) {
      message.warning("请输入密码！");
    } else if (!codeValue) {
      message.error('请输入验证码')
    } else {
      const parames = {
        loginName, //登录账号
        loginType: "PC", //登录设备
        password, //登录密码
        currentSystemType: "FOREGROUND_SYSTEM",
        captcha: {
          code: codeValue,
          serialNumber: suijishuValue,
        },
      };
      const { code, msg, data } = (await postContextLogin(parames)) as {
        code: number;
        msg: string;
        data: ILoginData;
      };
      if (code === 20000) {
        // message.success("登录成功！");
        sessionStorage.setItem("token", data.token);
        const getItemValue: ISessionUserData = {
          userName: data.userName,
          userId: data.userId,
        };
        sessionStorage.setItem("userInfo", JSON.stringify(getItemValue));
        sessionStorage.setItem("tabsTree", JSON.stringify(data.tree)); // 菜单tabs
        if (data.tree.length > 0) {
          const defaultMenu: {
            defaultOpenKeys: string[],
            defaultSelectedKeys: string[],
          } = {
            defaultOpenKeys: [],
            defaultSelectedKeys: []
          }; // 判断是否
          handleOneUrl(data.tree, defaultMenu)
          sessionStorage.setItem("keyPath", JSON.stringify(defaultMenu.defaultSelectedKeys));
          getAllDictionaryEntries(() => {
            navigate(defaultMenu.defaultSelectedKeys[0]);
          })
          
        } else {
          message.error('当前账号暂无权限')
        }
      } else {
        console.log(msg)
        message.error(msg);
        handleImageRenovate()
      }
    }
  };
  // enter 登录
  const handleKeyDown = (code: { key: string }) => {
    if (code.key === "Enter") {
      handleLogin();
    }
  };
  return (
    <LoginBox>
      <TopBox>
        <div className="logo"></div>
        <div className="logo_title"></div>
      </TopBox>
      <ConfigProvider
        theme={{
          token: {
            controlHeight: useWindowFontSize(51),
          },
          components: {
            Button: {
              contentFontSize: useWindowFontSize(18),
              controlHeight: useWindowFontSize(51),
            },
            Input: {
              controlHeight: useWindowFontSize(51),
            }

          }
        }}
      >
        <CardBox>
          <div className="title">登陆账户</div>
          <Input
            style={{ margin: "1rem 0" }}
            // size="large"
            placeholder="请输入您的登陆账号"
            value={loginName}
            onChange={(e) => setLoginName(e.target.value)}
          />
          <Input.Password
            style={{ margin: "1rem 0" }}
            // size="large"
            placeholder="请输入您的密码"
            value={password}
            onChange={(e) => setPassword(e.target.value)}

          />
          <div className="yanzhengma">
            <Input
              // size="large"
              placeholder="请输入图形验证码"
              onChange={(e) => setCodeValue(e.target.value)}
              onKeyDown={handleKeyDown}
            // style={{ width: "16rem", fontSize: '1.6rem' }}
            />
            <img
              onClick={handleImageRenovate}
              className="image_style"
              src={imageBase64}
              alt="服务器断开链接，请联系管理员"
            />
          </div>
          <Button
            onClick={() => handleLogin()}
            type="primary"
            block
            style={{ marginTop: "1rem" }}
          >
            登录
          </Button>
        </CardBox>
      </ConfigProvider>

    </LoginBox>
  );
};

export default LoginPage;
